package worker

import (
	"distributed/message"
	"distributed/parser"
	"fmt"
)

const (
	ThreadNum = 3
)

type (
	ResultChan chan message.ReptileResp
)

var (
	resultChan chan message.ReptileResult
	taskChan   chan message.ReptileReq
)

func PushResult() {
	taskChan = make(chan message.ReptileReq, ThreadNum)
	resultChan = make(chan message.ReptileResult, 100)
	for {
		result := <-resultChan
		client.pushResult(result)
	}
}

//func PullTask() message.ReptileReq {
//	client.pullTask()
//}

func PostFunction() {
	//_ = client.Ready("NEW")
	for {
		httpFunc()
	}
}

func httpFunc() {
	defer func() {
		//_ = client.Ready("")
		if err := recover(); err != nil {
			//fmt.Printf("[ httpFunc recover ] %v\n", err)
		}
	}()
	//task := <-taskChan
	task := client.pullResult()
	var (
		respBytes []byte
		err       error
	)
	fmt.Printf("[ httpFunc ] task: %#v\n", task)
	switch task.Function {
	case parser.CommentApiParser:
		url := "https://music.163.com/song?id=" + task.URL
		songDetailBytes, err := normalClient("GET", url, nil)
		if err != nil {
			resultChan <- message.ReptileResult{
				ReptileReq: message.ReptileReq{
					Method: task.Method,
					URL:    task.URL,
				},
				ReptileResp: message.ReptileResp{
					Status: 200,
				},
			}
			fmt.Println("[ parser.CommentApiParser ] error: ", err)
			return
		}

		songDetail := parser.GetFunction(parser.SongDetailParser)(string(songDetailBytes))
		songDetail.Song.SongID = task.URL
		resultChan <- message.ReptileResult{
			ReptileReq: message.ReptileReq{
				Method:   task.Method,
				URL:      url,
				Function: parser.SongDetailParser,
			},
			ReptileResp: *songDetail,
		}

		respBytes, err = NetEasyMusicClient(task.URL, task.Limit, task.Offset)
		if err != nil {
			resultChan <- message.ReptileResult{
				ReptileReq: message.ReptileReq{
					Method: task.Method,
					URL:    task.URL,
				},
				ReptileResp: message.ReptileResp{
					Status: 200,
				},
			}
			fmt.Println("[ parser.CommentApiParser ] error: ", err)
			return
		}

	default:
		respBytes, err = normalClient(task.Method, task.URL, nil)
		if err != nil {
			resultChan <- message.ReptileResult{
				ReptileReq: message.ReptileReq{
					Method: task.Method,
					URL:    task.URL,
				},
				ReptileResp: message.ReptileResp{
					Status: 200,
				},
			}
			fmt.Println("[ normalClient ] error: ", err)
			return
		}
	}

	respStr := string(respBytes)
	// todo : 编码格式转换
	//if respStrUtf8, err := simplifiedchinese.GBK.NewDecoder().String(respStr); err == nil {
	//	respStr = respStrUtf8
	//}

	parserResult := parser.GetFunction(task.Function)(respStr)
	if parserResult != nil {
		parserResult.Status = 200
		parserResult.Result = respStr
		resultChan <- message.ReptileResult{
			ReptileReq: message.ReptileReq{
				Method:   task.Method,
				URL:      task.URL,
				Function: task.Function,
				Limit:    task.Limit,
				Offset:   task.Offset,
			},
			ReptileResp: *parserResult,
		}
	}
}
